
import JsBarcode from 'jsbarcode';
// import Hybrid from '@/components/uzone-hybrid';
import Preview from '../repay/components/preview/index';
import HederTop from '@/components/header-top'

export default {
  name: 'repay-detail',
  components: {
    Preview,
    HederTop
  },
  data () {
    return {
      extensionamount:0,
      payinType:'',
      previewData: {},
      type: '',
      showConfirmDialog: false, // 显示确认弹框
      repayForm: {
        repayType: '711', // 还款方式
        amount: '', // 还款金额
      },
      repayCodeImg: '',
      showRepayCode: false,
      couponAmount: 0, // 使用的优惠券金额
      repayType: '', // 还款方式
      companyCode: '', // 公司编号
      channelCode: '', // 还款渠道编号
      repayUrl: '', // Xendit还款地址
      stepMethodMap: {
        payso: {
          'rd pawnshop': {
            steps: [
              'Get to RD Pawnshop',
              'Please inform the staff that the Pay Bills to PAYSO',
              'Contact customer service on the spot if there is a problem',
            ],
            minMoney: 0
          },
          'gcash': {
            steps: [
              'Go to Gcash wallet, click "Pay Bills" and select bill payment',
              'Click on "Loans" and search for "PAYSO"',
              'Enter the repayment interface, fill in the information, order number, account name, amount, email, and click [NEXT]' +
               '<br /><br />7-15 Digit Remit Number：15-digit repayment code starting with "PSP"<br /> Account Name：Fill in "PAYSO" <br />Amount：Repayment Amount'
            ],
            minMoney: 100,
          },
          '7-11': {
            steps: [
              'Click the button below to enter the repayment amount to generate a repayment code',
              'Bring your valid ID to the offline 7-11 store',
              'Tell the cashier you will be paying Payso',
              'Show the clerk the repayment code generated in the APP',
              'Payment after confirming the order information',
              'After successful payment, keep the payment voucher'
            ],
            minMoney: 100
          },
          'instapay':{
            steps: [
              'Enter the Gcash wallet and find "Transfer" on the home page',
              'Click "view all" in the lower right corner',
              'Search for "Netbank"',
              'Follow the prompts on the page to fill in the payment information',
              'Confirm payment information and make payment',
            ],
            minMoney: 1
          },
          'qr': {
            steps: [
              'Click the button below to enter the repayment amount',
              'Generate a repayment code after confirming the amount',
              'After saving the repayment code, scan the code in the e-wallet to repay'
            ],
            minMoney: 300,
          },
        },
        skypay: {
          'gcash': {
            steps: [
              'Check your GCASH account balance have enough amount.',
              'Tap the Pay Bills icon and add a new biller.',
              'Pay the biller.',
              'Enter the amout to pay.'
            ],
            minMoney: 0
          },
          'qr': {
            steps: [
              'Click the button below to enter the repayment amount',
              'Generate a repayment code after confirming the amount',
              'After saving the repayment code, scan the code in the e-wallet to repay'
            ],
            minMoney: 300,
          },
          'paymaya': {
            steps: [
              'Open PayMaya and go to the home page and select Bills.',
              'Choose Loans in Pay Bills.',
              'Choose SkyPay in Loans.',
              'Fill in the order information to pay.'
            ],
            minMoney: 0
          },
          '7-11': {
            steps: [
              'Click the button below to enter the amount to generate a repayment code.',
              'Go to store 7-11.',
              'Show the repayment code to the clerk for repayment.',
              'Keep the voucher after repayment.',
            ],
            minMoney: 0
          },
          'rd pawnshop': {
            steps: [
              'Visit any RD Pawnshop Branches.Please tell cashier “Pay bills to SkyPay-API”.',
              'Fill in bills form.',
              'Hand in cash and form to cashier.',
              'Get bills payment receipt *Please keep Receipt properly.'
            ],
            minMoney: 0
          },
          'm lhuillier': {
            steps: [
              'Get to M.Lhuillier',
              'Get the M.Lhuillier bills payment form.',
              'Fill up the form.'
            ],
            minMoney: 0
          }
        },
        xw: {
          'gcash': {
            steps: [
              'Click the button below to enter Gcash.',
              'Sign in with mobile phone verification code.',
              'Pay the order after confirmation.',
              'Return to the home page of the app after successful payment.'
            ],
            minMoney: 1,
          },
          'paymaya': {
            steps: [
              'Click the button below to enter PayMaya.',
              'Login and confirm order information.',
              'Pay the order after confirmation.',
              'Return to the home page of the app after successful payment.'
            ],
            minMoney: 1
          },
          'grabpay': {
            steps: [
              'Click the button below to enter Grabpay.',
              'Login and confirm order information.',
              'Pay the order after confirmation.',
              'Return to the home page of the app after successful payment.',
            ],
            minMoney: 1
          },
          '7-11': {
            steps: [
              'Visit your nearest 7-11 branch before the payment code is expired.',
              'Tell the cashier/staff that you will be making a payment to XENDIT.',
              'Show the payment code or barcode to the cashier.',
              'Confirm that the amount shown on the Application or Website is the same with the one that the cashier had,then proceed to make payment.',
              'Keep the Payment proof from 7-11.',
              'Payment has successfully completed.'
            ],
            minMoney: 50
          },
          'instapay': {
            steps: [
              'Click the button below to enter the amount to generate a repayment code.',
              'Use Grabpay, Gcash, PayMaya and other commonly used electronic wallets to choose to transfer to AUB bank, enter the corresponding information and repayment code to transfer.',
              'When entering the repayment information, enter the repayment code in the account and enter the amount to be repaid. If there is no other information, you can fill in at will.',
              'After the transfer is successful, keep the voucher.'
            ],
            minMoney: 100
          },
          'qr': {
            steps: [
              'Click the button below to enter the repayment amount',
              'Generate a repayment code after confirming the amount',
              'After saving the repayment code, scan the code in the e-wallet to repay'
            ],
            minMoney: 300,
          },
        },
        companyCode4: {
          'gcash': {
            steps: [
              'Open your Gcash app.',
              'Tap the “Pay Bills” button.',
              'Search for “Dragon Loans” using the search button located at the upper left of the screen.',
              `Fill in the required details,Please fill out the following information: <br/>
               ·Reference Number: Payment code you given by merchant<br/>
               ·Contact Number: Repayment code generated in the APP<br/>
               ·Amount: Amount due of your payment code
              `,
              'Click “Next” after filling out the form, you will then be redirected to the confirmation page.',
              'Click on “confirm”, you will be redirected to an e-receipt page after payment is successful.',
            ],
            minMoney: 500,
          },
          'paymaya': {
            steps: [
              'Open your PayMaya App.',
              'Tap the “Bills” button.',
              'Search for “Dragon Loans” using the search button located at the upper left of the screen.',
              `Fill in the required details,Please fill out the following information：<br/>
               ·Account Number: Repayment code generated in the APP<br/>
               ·Amount: Amount due of your payment code<br/>
               ·Mobile Number: Your personal mobile number
              `,
              'Click “Continue” after filling out the form, you will then be redirected to the processing page.',
              'Page will be automatically updated after payment is processed and Done.'
            ],
            minMoney: 500
          },
          'grabpay': {
            steps: [
              'Click the button below to enter Grabpay.',
              'Login and confirm order information.',
              'Pay the order after confirmation.',
              'Return to the home page of the app after successful payment.',
            ],
            minMoney: 500
          },
          '7-11': {
            steps: [
              'Visit your nearest 7-Eleven branch before the payment code is expired.',
              'Tell the cashier/staff that you will be making a payment to XENDIT.',
              'Shows the payment code or barcode to the cashier.',
              'Confirm that the amount shown on the Application or Website is the same with the one that the Cashier had, then proceed to make payment.',
              'Keep the Payment proof from 7-Eleven.',
              'Payment has successfully completed.'
            ],
            minMoney: 500
          },
          'ecpay': {
            steps: [
              'Visit your nearest EcPay outlet branch before payment code expires.',
              'Tell the cashier/staff that you will be making a payment for XENDIT under ECPay eCash Service.',
              `You will receive a Transaction Form Slip (differs per outlet).<br>
               Please fill out the following information:<br/>
               Transaction Type: ECCash<br/>
               Name: Your Name<br/>
               Biller: Xendit (for Xendit Biller) / Merchant Name (for Merchant Biller)<br/>
               Control No./ Account No./ Reference No.: Repayment code generated in the APP<br/>
               Amount: Amount due of your payment code
              `,
              'Give the filled out slip to the cashier/staff with your payment (cash only).',
              'Keep the payment proof from ECPay.'
            ],
            minMoney: 500
          },
          'm lhuillier': {
            steps: [
              'Visit your nearest M Lhuillier outlet branch before payment code expires.',
              'Tell the cashier/staff that you will be making a Bills Payment (not a remittance).',
              `You will be given a SEND MONEY FORM (White Form) to fill-up.<br/>
               Please fill out the following information:<br/>
               ·Date: Date of Payment<br/>
               ·Payment to: DRAGONPAY<br/>
               ·Account Name: Your Name<br/>
               ·Account Number: Repayment code generated in the APP<br/>
               ·Contact Number: Your mobile number
              `,
              'Give the filled out slip to the cashier/staff with your payment (cash only), The cashier will charge you an extra fee for their service.',
              'You will receive a receipt as proof of payment.'
            ],
            minMoney: 500
          },
          'instapay': {
            steps: [
              'Click the button below to enter the amount to generate a repayment code.',
              'Use Grabpay, Gcash, PayMaya and other commonly used electronic wallets to choose to transfer to AUB bank, enter the corresponding information and repayment code to transfer.',
              'When entering the repayment information, enter the repayment code in the account and enter the amount to be repaid. If there is no other information, you can fill in at will.',
              'After the transfer is successful, keep the voucher.'
            ],
            minMoney: 500
          },
          'qr': {
            steps: [
              'Click the button below to enter the repayment amount',
              'Generate a repayment code after confirming the amount',
              'After saving the repayment code, scan the code in the e-wallet to repay'
            ],
            minMoney: 300,
          },
        },
      },
      repayStep: [], // 还款步骤
      minMoney: 0, // 最小还款金额
      hasQueryCoupon: false, // 已查询优惠券
      hasQueryOrder: false, // 已查询订单详情
      repayCode: '', // 还款码
      productId: '',
    };
  },
  computed: {
    isGetRepayCode() {
      // 判断是否已经获取合同金额和优惠券金额，然后再去获取还款码
      // const { companyCode, hasQueryCoupon, hasQueryOrder, repayType } = this;
      // return hasQueryCoupon && hasQueryOrder && '2' === companyCode && '7-11' !== repayType;
      // 判断是否已经获取合同金额和优惠券金额，然后再去获取还款码
      // const { companyCode, hasQueryCoupon, hasQueryOrder, repayType } = this;
      // return hasQueryCoupon && hasQueryOrder && '2' === companyCode && '7-11' !== repayType;
      const { companyCode, hasQueryOrder, repayType } = this;
      let result = false;
      if (hasQueryOrder ) {
        if ('2' === companyCode && '7-11' !== repayType) {
          result = true;
        }
        if (companyCode === '5') {
          if (repayType === 'Rd Pawnshop' || repayType === 'Gcash') {
            this.type = 'PAYSO';
            result = true;
          }
        }
      }
      // 当已经查询优惠券已经查询订单信息并且支付渠道是2(SkyPay)并且支付方式不是7-11的时候展示skypay Code
      // return hasQueryCoupon && hasQueryOrder && '2' === companyCode && '7-11' !== repayType;
      return result;
    }
  },
  methods: {
    // handleDown () {
    //   const a = document.createElement('a')
    //   a.download = 'img.png'
    //   a.href = this.repayCodeImg
    //   document.body.appendChild(a)
    //   a.click()
    //   document.body.removeChild(a)
    // },
    // 根据订单号获取订单信息
    getOrderByOrderId() {
      const params = {
        orderNo: this.orderId,
      };
      this.$api.getOrderByOrderId(params).then(res => {
        const { status, error, msg, data } = res;
        if ('1' === status && ('00000000' === error || '0000' === error) && data) {
          this.previewData = data;
          this.hasQueryOrder = true;
          if (this.isGetRepayCode) {
            this.getRepayCode();
          }
        } else {
          this.$toast(msg);
        }
      });
    },
    // 跳转还款帮助页
    goHelp() {
      this.$router.push({
        path: '/help',
      });
    },
    // 确认还款信息弹框关闭前 restRepay
    beforeClose(action, done) {
      if ('confirm' === action) {

        if(this.payinType === 'EXTENSION'){
          // 还款详情页 - 展期 - 点击
          // this.$hybrid.action('ee', {
          //   content: 'repay_extension_click',
          //   value: {
          //     productId: this.productId || ''
          //   },
          // });
        } else {
          // 还款详情页 - 还款 - 点击
          // this.$hybrid.action('ee', {
          //   content: 'repay_repayment_click',
          //   value: {
          //     productId: this.productId || ''
          //   },
          // });
        }

        const amount = this.repayForm.amount;
        const { restRepay } = this.previewData;

        if (/^[1-9]\d*$/.test(amount)) {
          const minMoney = this.minMoney;

          if (['2','5'].includes(this.companyCode)) {
            // 当挂账金额大于500时，限制输入的最小还款金额不得小于等于500；
            if (restRepay > 500 && amount <= 500) {
              this.$toast(this.$tc('repayCodeImgAmountTips1', 1, { amount: 500 })); // 最小还款金额要大于500
              done(false);
              return;
            }
            // 当挂账金额小于等于500，大于0时，限制输入的还款金额必须大于等于挂账金额；
            if (restRepay <= 500 && restRepay > 0 && amount < restRepay) {
              this.$toast(this.$tc('repayCodeImgAmountTips2', 1, { amount: restRepay })); // 还款金额必须大于等于挂账金额
              done(false);
              return;
            }
            // 当挂账金额为0时，限制输入的最小还款金额不得小于等于200
            if (restRepay <= 0 && amount <= 200) {
              this.$toast(this.$tc('repayCodeImgAmountTips3')); // 最小还款金额不得小于等于200
              done(false);
              return;
            }
          } else if (['4'].includes(this.companyCode)) {
            // 7-11限制输入的最大还款金额不得超过10000；
            if (this.repayType === '7-11' && amount > 10000) {
              this.$toast(this.$tc('repayCodeImgAmountTips4'), 1); // 最小还款金额要大于500
              done(false);
              return;
            }
            // 当挂账金额大于500时，限制输入的最小还款金额不得小于等于500；
            if (restRepay > minMoney && amount <= minMoney) {
              this.$toast(this.$tc('repayCodeImgAmountTips1', 1, { amount: minMoney })); // 最小还款金额要大于500
              done(false);
              return;
            }
            // 当挂账金额小于等于500，大于0时，限制输入的还款金额必须大于等于挂账金额；
            if (restRepay <= minMoney && restRepay > 0 && amount < restRepay) {
              this.$toast(this.$tc('repayCodeImgAmountTips2', 1, { amount: restRepay })); // 还款金额必须大于等于挂账金额
              done(false);
              return;
            }
            // 当挂账金额为0时，限制输入的最小还款金额不得小于等于200
            // if (restRepay <= 0 && amount <= 200) {
            //   this.$toast(this.$tc('repayCodeImgAmountTips3')); // 最小还款金额不得小于等于200
            //   done(false);
            //   return;
            // }
          } else if (amount <= minMoney) {
            this.$toast(this.$tc('repayCodeImgAmountTips1', 1, { amount: minMoney })); // 最小还款金额要大于minMoney
            done(false);
            return;
          }

          this.getRepayCode(amount, true).then(() => {
            if (this.repayUrl) {
              // 用APP打开浏览器页面
              this.$hybrid.action('openBrowser', {
                param: {
                  url: this.repayUrl,
                  type: '0',
                },
                callback: res => {
                  // eslint-disable-next-line no-console
                  console.log(res);
                }
              });
            }
            // 完成后关闭弹框
            done();
          }).catch(() => {
            done(false);
          });
        } else {
          this.$toast(this.$tc('plsInputCorrectAmount')); // 请输入正确的还款金额
          done(false);
        }
      } else {
        done();
      }
    },
    // 显示还款信息输入确认弹框
    handleShowConfirmDialog() {
      this.repayForm.amount = +this.previewData.restRepay - this.couponAmount;
      if(this.payinType === 'EXTENSION'){
        this.repayForm.amount = this.extensionamount
      }
      this.showConfirmDialog = true;
    },
    // 获取还款码
    getRepayCode(amount, showCodeImg) {
      const { orderId, companyCode, channelCode, previewData: { restRepay }, couponAmount } = this;
      const params = {
        productId:this.previewData.productId,
        orderNo:orderId,
        channelCode,
        paymentCompanyCode: companyCode,
        // amount:amount,
        payinType: this.payinType==='EXTENSION'?'EXTENSION':'REPAY', // EXTENSION:展期 REPAY:还款
        amount:amount || restRepay,



        // orderId,
        // channelCode,
        // paymentCompanyCode: companyCode,
        // payinType: this.payinType==='EXTENSION'?'EXTENSION':'REPAY', // EXTENSION:展期 REPAY:还款
      };
      if(this.payinType==='EXTENSION'){
        params.amount = this.extensionamount
      };
      return this.$api.createMixRepayCharge(params).then(res => {
        const { status, data } = res;
        if ('1' === status && data) {
          if (data.indexOf('http') > -1) {
            this.type = 'Xendit';
            this.repayUrl = data;
          } else {
            const contractNumber = data;
            this.repayCode = data;
            if (contractNumber.indexOf('SKY') >= 0) {
              this.type = 'SKY';
            } else if (contractNumber.indexOf('MSP') >= 0) {
              this.type = 'MSP';
            }
            if (showCodeImg) {
              this.showRepayCode = true;
              let repayInfo = null;
              if (data.indexOf(',') > -1) {
                repayInfo = data.split(',');
                this.repayCode = repayInfo[1];
              }
              if (!(['4'].includes(companyCode) && ['ECPay', 'M Lhuillier', 'Gcash', 'Paymaya'].includes(this.repayType))) {
                if (this.repayType === 'QR') {
                 this.repayCodeImg = data
                } else {
                  this.$nextTick(() => {
                    JsBarcode('#repayCodeImg', repayInfo ? repayInfo[0] : data);
                  });
                }
              }
            }
          }
        }
      });
    },
    // 使用了优惠券
    handleCouponAmount(amount) {
      this.couponAmount = amount;
      this.hasQueryCoupon = true;
      if (this.isGetRepayCode) {
        this.getRepayCode();
      }
    },
    // 转换公司
    switchRepayStep() {
      const repayType = this.repayType.toLowerCase();
      const companyCode = String(this.companyCode);

      if ('2' === companyCode) {
        const method = this.stepMethodMap.skypay[repayType];
        this.repayStep = method.steps || [];
        this.minMoney = method.minMoney;
      } else if (['1'].includes(companyCode)) {
        const method = this.stepMethodMap.xw[repayType];
        this.repayStep = method.steps || [];
        // Wallyt的支付方式最低金额都置为100
        this.minMoney = '1' === companyCode ? 100 : method.minMoney;
      } else if (['4'].includes(companyCode)) {
        const method = this.stepMethodMap.companyCode4[repayType];
        this.repayStep = method.steps || [];
        this.minMoney = method.minMoney;
      }else if (['5'].includes(companyCode)) {
        const method = this.stepMethodMap.payso[repayType];
        this.repayStep = method.steps || [];
        this.minMoney = method.minMoney;
      }
    },
    // 复制还款码
    handleCopy() {
      const me = this;
      // const hybrid = new Hybrid(this.$os.android ? 'android' : 'ios');
      this.$hybrid.action('copyPaste', {
        param: { text: this.repayCode },
        callback (data) {
          me.$toast('Repayment code copied');
          // console.log(data);
        }
      });
    },
  },
  created () {
    // this.$hybrid.action('ee', {
    //   content: 'repay_page_payment_channel'
    // });

    const { orderId, repayType, companyCode, channelCode ,payinType,amount, productId} = this.$route.query;
    this.orderId = orderId;
    this.repayType = repayType;
    this.companyCode = String(companyCode);
    this.channelCode = channelCode;
    this.payinType = payinType;
    this.extensionamount = amount;
    this.productId = productId || '';

    // 还款详情页 - 页面 - 曝光
    // this.$hybrid.action('ee', {
    //   content: 'repay_page_show',
    //   value: {
    //     productId: this.productId || ''
    //   },
    // });

    this.getOrderByOrderId();
    this.switchRepayStep();
  }
};
